import "../lib/jquery.js";
import axios from "../lib/axios.js";

$(function () {
  const authorization = localStorage.getItem("authorization"),
    user = JSON.parse(localStorage.getItem("user"));
  // 没登录跳转回首页
  if (!authorization) {
    location.href = "login.html";
  }

  $("form").submit(function (e) {
    e.preventDefault();
    var formData = {
      id: user.id,
    };
    $("form input").each(function () {
      formData[$(this).attr("class")] = $(this).val();
    });

    var pwdReg = /\w{6,12}/;

    if (!formData.newPassword) return layer.msg("请填写新密码", { icon: 5 });
    if (!formData.rNewPassword)
      return layer.msg("请填写确认新密码", { icon: 5 });

    if (formData.newPassword != formData.rNewPassword)
      return layer.msg("两次密码不一致", { icon: 5 });

    if (!pwdReg.test(formData.oldPassword))
      return layer.msg("旧密码格式不正确", { icon: 5 });
    if (!pwdReg.test(formData.newPassword))
      return layer.msg("新密码格式不正确", { icon: 5 });

    axios
      .post("http://localhost:9000/users/rpwd", formData, {
        headers: {
          authorization: localStorage.getItem("authorization"),
        },
      })
      .then(({ data }) => {
        if (data.code === 1 || data.code === 401) {
          localStorage.removeItem("authorization");
          localStorage.removeItem("user");
          alert(data.message);

          location.href = "login.html";
        } else {
          $(".error").show().text(data.message);
        }
      });
  });
});
